1
|
|
|
import type { ClassNamed, ClassHash } from "./main.types" |
2
|
|
|
import type { Falsy } from "./ts-swiss.types" |
3
|
|
|
import { EMPTY_ARRAY } from "./consts.json" |
4
|
|
|
|
5
|
|
|
const { |
6
|
|
|
defineProperty: $defineProperty |
7
|
|
|
} = Object |
8
|
|
|
, stringifyProperty: SymbolConstructor["toPrimitive"] | "valueOf" | "toString" = Symbol.toPrimitive |
9
|
|
|
, StringifyDescriptor = {value: classNamedToString} |
10
|
|
|
|
11
|
|
|
export { |
12
|
|
|
wrapper, |
13
|
|
|
resolver, |
14
|
|
|
picker, |
15
|
|
|
joinWithLead |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
function wrapper<T extends Record<string, any>>( |
19
|
|
|
destination: T, |
20
|
|
|
className: undefined | string |
21
|
|
|
) { |
22
|
|
|
//@ts-expect-error |
23
|
|
|
destination["className"] = className |
24
|
|
|
|
25
|
|
|
if (!destination.hasOwnProperty(stringifyProperty)) |
26
|
|
|
$defineProperty(destination, stringifyProperty, StringifyDescriptor) |
27
|
|
|
|
28
|
|
|
return destination as T & ClassNamed |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
function picker( |
32
|
|
|
vocabulary: undefined | Record<string, ClassHash>, |
33
|
|
|
keys: string[] |
34
|
|
|
) { |
35
|
|
|
if (!vocabulary) |
36
|
|
|
return keys |
37
|
|
|
|
38
|
|
|
for (let i = keys.length; i--;) { |
39
|
|
|
const key = keys[i] |
40
|
|
|
, val = vocabulary[key] |
41
|
|
|
|
42
|
|
|
if (val !== undefined) |
43
|
|
|
keys[i] = val |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return keys |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
function resolver( |
50
|
|
|
vocabulary: undefined | Record<string, ClassHash>, |
51
|
|
|
actions: Record<string, ClassHash | boolean> |
52
|
|
|
) { |
53
|
|
|
// https://jsbench.me/q8kltjsdwy |
54
|
|
|
const $return: string[] = [] |
55
|
|
|
|
56
|
|
|
// https://jsbench.me/prkm3gn4ji |
57
|
|
|
for (const key in actions) { |
58
|
|
|
const act = actions[key] |
59
|
|
|
|
60
|
|
|
if (act === undefined || act === true) |
61
|
|
|
// https://jsbench.me/p3km3fg4e7 |
62
|
|
|
$return.push(key) |
63
|
|
|
else if (act) |
64
|
|
|
// https://jsbench.me/p3km3fg4e7 |
65
|
|
|
$return.push(act) |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $return.length === 0 |
69
|
|
|
? EMPTY_ARRAY |
70
|
|
|
: picker(vocabulary, $return) |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
//TODO Consider returning `undefined` on empty string |
74
|
|
|
function joinWithLead(value: Falsy|ClassHash, arr: undefined | string | readonly string[]) : string { |
75
|
|
|
const str1 = value || "" |
76
|
|
|
if (!(arr && arr.length)) |
77
|
|
|
return str1 |
78
|
|
|
|
79
|
|
|
const str2 = typeof arr === "string" ? arr : arr.join(" ") |
80
|
|
|
if (!str1) |
81
|
|
|
return str2 |
82
|
|
|
|
83
|
|
|
return `${str1} ${str2}` |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
function classNamedToString(this: ClassNamed) { |
87
|
|
|
//TODO `?? ""` |
88
|
|
|
return this.className |
89
|
|
|
} |
90
|
|
|
|